package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.UserMapper;
import com.sky.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class   LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();


        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);
        log.info("user:{}",user);
        //2、处理各种异常情况（用户名不存在、密码不对、角色不一致、账号被锁定）
        if (user == null || user.getRole()!=userLoginDTO.getRole()) {
            //账号不存在或者角色对不上——抛出账号未发现异常
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //password= DigestUtils.md5DigestAsHex(password.getBytes());   //这个spring的方法可以将密码转换为密文
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if(Objects.equals(user.getStatus(), "0")){
            throw new PasswordErrorException("账号已被冻结，请联系管理员！");
        }
        //3、返回实体对象
        return user;
    }
}
